<template>
  <view class="hb-flex hb-items-center hb-gap-2 hb-mb-4 hb-w-57">
    <tm-time-picker
      v-model="startTime"
      :defaultValue="startTime"
      :showDetail="showDetail"
      :immediate-change="true"
      format="YYYY-MM-DD"
      start="1949/6/15 00:00:00"
      end="2099/12/31 23:59:59"
    >
      <view
        class="hb-w-25.25 hb-h-7 hb-bg-[#F2F3F5] hb-rounded-md hb-flex hb-items-center hb-justify-center"
      >
        <tm-text :label="time[0] || '开始时间'"></tm-text>
      </view>
    </tm-time-picker>
    <tm-text label="至" v-if="time[1] != longTermVal"></tm-text>
    <tm-time-picker
      v-if="time[1] != longTermVal"
      v-model="endTime"
      :defaultValue="endTime"
      :showDetail="showDetail"
      :immediate-change="true"
      format="YYYY-MM-DD"
      start="1949/6/15 00:00:00"
      end="2099/12/31 23:59:59"
    >
      <view
        class="hb-w-25.25 hb-h-7 hb-bg-[#F2F3F5] hb-rounded-md hb-flex hb-items-center hb-justify-center"
      >
        <tm-text :label="time[1] || '结束时间'"></tm-text>
      </view>
    </tm-time-picker>
  </view>
  <tm-checkbox
    label="长期有效"
    v-model:modelValue="longTerm"
    @change="handleChange"
    :follow-theme="false"
    color="#2878FF"
    :size="32"
  ></tm-checkbox>
</template>
<script setup lang="ts">
  import dayjs from 'dayjs';
  const showDetail = {
    year: true,
    month: true,
    day: true,
    hour: false,
    minute: false,
    second: false,
  };

  const props = defineProps({
    time: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
    longTermVal: {
      type: String,
      default: '长期',
    },
  });

  const emtis = defineEmits(['update:time']);

  const startTime = ref<string>('');
  const endTime = ref<string>('');
  const longTerm = ref(false);

  watch(
    () => props.time,
    (newVal) => {
      startTime.value = newVal[0];
      if (newVal[1] == props.longTermVal) {
        longTerm.value = true;
        endTime.value = props.longTermVal;
      } else {
        longTerm.value = false;
        endTime.value = newVal[1];
      }
    },
    { immediate: true, deep: true },
  );

  watch([startTime, endTime, longTerm], () => {
    const time: string[] = [];
    startTime.value && (time[0] = dayjs(startTime.value).format('YYYY-MM-DD'));
    if (endTime.value == props.longTermVal) {
      time[1] = props.longTermVal;
    } else if (endTime.value) {
      time[1] = dayjs(endTime.value).format('YYYY-MM-DD');
    }
    console.log(time);

    emtis('update:time', time);
  });

  const handleChange = (val: boolean) => {
    if (val) {
      endTime.value = props.longTermVal;
    } else {
      endTime.value = '';
    }
  };
</script>
